package cn.com.spring.aspecti.impl;


import cn.com.spring.annotation.Around;
import cn.com.spring.annotation.Aspect;
import cn.com.spring.annotation.Async;
import cn.com.spring.annotation.Component;
import cn.com.spring.model.EntityInvocation;
import cn.com.utils.ThreadPoolUtils;
import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.Callable;

/**
 * 生成异步代理
 *
 * @author LiuGuodong
 * @date 2023/01/28
 */
@Aspect
@Slf4j
@Component
public class AsyncHandler {


    @Around(name = Async.class)
    public Object intercept(EntityInvocation entityInvocation) throws Throwable {
        log.info("Aspect 异步拦截 {}", "Around");
        Object result = null;
        EntityInvocation.MethodSignature method = entityInvocation.getMethod();
        Async annotation = method.getAnnotation(Async.class);
        //使用指定线程池
        if (annotation != null) {
            if (annotation.result()) {
                result = ThreadPoolUtils.submitTask(getCallable(entityInvocation), annotation.value());
            } else {
                ThreadPoolUtils.submitTask(getRunnable(entityInvocation));
            }
        } else {
            result = entityInvocation.proceed();
        }
        return result;
    }

    /**
     * 获得可调用
     *
     * @return {@link Callable}<{@link ?}>
     */
    private static Callable<?> getCallable(EntityInvocation entityInvocation) {
        return () -> {
            try {
                return entityInvocation.proceed();
            } catch (Throwable e) {
                throw new RuntimeException(e);
            }
        };
    }

    /**
     * 可运行
     *
     * @return {@link Runnable}
     */
    private static Runnable getRunnable(EntityInvocation entityInvocation) {
        return () -> {
            try {
                entityInvocation.proceed();
            } catch (Throwable e) {
                throw new RuntimeException(e);
            }
        };
    }


}
